package service

import (
	"context"
	"time"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/userInfo/glb"
	"gorm.io/gorm"
)

func (s *Service) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
	user := &models.User{AccountID: request.GetAccountID()}
	err := glb.DB.Take(user).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.LoginResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeNotAuth,
				Message: "用户不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return loginRespSvrErr, nil
	}

	if !user.Check(request.GetPasswordMD5()) {
		return &pb.LoginResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "密码错误",
		}}, nil
	}

	token := core.Token{
		Timestamp: time.Now().Unix(),
		LifeCycle: core.TokenTimeout,
		AccountID: user.AccountID,
		Name:      user.Name.String,
		Gender:    user.Gender.Int32,
		Type:      user.Type.Int32,
		IsManager: user.IsManager.Bool,
	}
	tokenStr := token.PackToken(glb.TokenCert)

	return &pb.LoginResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		Token:  tokenStr,
	}, nil
}
